package com.usian.behavior.service.impl

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.usian.behavior.mapper.ApUnLikeBehaviorMapper
import com.usian.behavior.service.ApBehaviorEntryService
import com.usian.behavior.service.UnLikeBehaviorService
import com.usian.model.behavior.dtos.UnLikesBehaviorDto
import com.usian.model.behavior.pojos.ApUnlikesBehavior
import com.usian.model.common.base.BaseServiceImpl
import com.usian.model.common.dtos.ResponseResult
import com.usian.model.common.enums.AppHttpCodeEnum
import com.usian.utils.threadlocal.AppThreadLocalUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.*

@Service
open class UnlikeBehaviorServiceImpl : BaseServiceImpl<ApUnLikeBehaviorMapper, ApUnlikesBehavior>(), UnLikeBehaviorService {
    @Autowired
    private lateinit var apBehaviorEntryService: ApBehaviorEntryService

    override fun unLike(dto: UnLikesBehaviorDto?): ResponseResult<*>? {
        val userId: Int? = dto?.run {
            //参数校验
            if (type.toInt() != 0 && type.toInt() != 1) return paramError
            if (articleId == null) return paramError
            //用户或者设备必须有一个     let返回最后一行代码   返回userId = ApUser.id
            AppThreadLocalUtils.getUser().let {
                if ((it == null || it.id == null) && equipmentId == null) return paramError
                it?.id
            }
        }
        var behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(userId, dto?.equipmentId)
        return if (behaviorEntry != null) {
            var unlike = getOne(QueryWrapper<ApUnlikesBehavior>().eq("article_id", dto?.articleId).eq("entry_id", behaviorEntry.id))
            if (unlike == null && dto?.type == 0.toShort()) {
                unlike = ApUnlikesBehavior().apply {
                    entryId = behaviorEntry.id ?: dto?.equipmentId
                    articleId = dto?.articleId
                    type = dto?.type?.toInt()
                    createdTime = Date()
                }
                save(unlike)
            } else {
                unlike.type = dto?.type?.toInt()
                updateById(unlike)
            }
            okResult
        } else ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "实体不存在")
    }
}